package com.zyk.scaffold.mq.rocket.business.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.zyk.scaffold.mq.rocket.business.order.pojo.request.CreateOrderRequest;
import com.zyk.scaffold.mq.rocket.business.order.producers.OrderlyProducer;
import com.zyk.scaffold.mq.rocket.business.order.service.OrderService;
import com.zyk.scaffold.mq.rocket.globs.constants.OrderStatus;
import com.zyk.scaffold.mq.rocket.repositorys.entity.TOrder;
import com.zyk.scaffold.mq.rocket.repositorys.mapper.TOrderMapper;
import org.apache.rocketmq.client.apis.message.Message;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private TOrderMapper orderMapper;

    @Resource
    private OrderlyProducer orderlyProducer;

    @Override
    public boolean createOrder(CreateOrderRequest createOrderRequest) {
        boolean flag = true;
        try {
            String supplierId = createOrderRequest.getSupplierId();
            String goodsId = createOrderRequest.getGoodsId();
            TOrder order = new TOrder();
            order.setOrderId(UUID.randomUUID().toString().substring(0, 32));
            order.setOrderType("1");
            order.setCityId(createOrderRequest.getCityId());
            order.setPlatformId(createOrderRequest.getPlatformId());
            order.setUserId(createOrderRequest.getUserId());
            order.setSupplierId(supplierId);
            order.setGoodsId(goodsId);
            order.setOrderStatus(OrderStatus.ORDER_CREATED.getValue());
            order.setRemark("");

            LocalDateTime now = LocalDateTime.now();
            order.setCreateBy("admin");
            order.setCreateTime(now);
            order.setUpdateBy("admin");
            order.setUpdateTime(now);

            int currentVersion = storeServiceApi.selectVersion(supplierId, goodsId);
            int updateRetCount = storeServiceApi.updateStoreCountByVersion(currentVersion, supplierId, goodsId, "admin", currentTime);

            if(updateRetCount == 1) {
                // 如果出现SQL异常 入库失败, 那么要对 库存的数量 和版本号进行回滚操作
                orderMapper.insert(order);
            }
            //	没有更新成功 1 高并发时乐观锁生效   2 库存不足
            else if (updateRetCount == 0){
                flag = false;	//	下单标识失败
                int currentStoreCount = storeServiceApi.selectStoreCount(supplierId, goodsId);
                if(currentStoreCount == 0) {
                    //{flag:false , messageCode: 003 , message: 当前库存不足}
                    System.err.println("-----当前库存不足...");
                } else {
                    //{flag:false , messageCode: 004 , message: 乐观锁生效}
                    System.err.println("-----乐观锁生效...");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            // 	具体捕获的异常是什么异常
            flag = false;
        }

        return flag;
    }

    @Override
    public boolean sendOrderlyMessage4Pkg(String userId, String orderId) {
        List<Message> messageList = new ArrayList<>();

        Map<String, Object> param1 = new HashMap<String, Object>();
        param1.put("userId", userId);
        param1.put("orderId", orderId);
        param1.put("text", "创建包裹操作---1");

        String key1 = UUID.randomUUID().toString() + "$" +System.currentTimeMillis();
        Message message1 = orderlyProducer.newMessageBuilder(key1, JSONObject.toJSONString(param1));
        messageList.add(message1);


        Map<String, Object> param2 = new HashMap<String, Object>();
        param2.put("userId", userId);
        param2.put("orderId", orderId);
        param2.put("text", "发送物流通知操作---2");

        String key2 = UUID.randomUUID().toString() + "$" +System.currentTimeMillis();
        Message message2 = orderlyProducer.newMessageBuilder(key2, JSONObject.toJSONString(param2));

        messageList.add(message2);

        //	顺序消息投递 是应该按照 供应商ID 与topic 和 messagequeueId 进行绑定对应的
        //  supplier_id

        TOrder order = orderMapper.selectById(orderId);
        int messageQueueNumber = Integer.parseInt(order.getSupplierId());

        // TODO 对应的顺序消息的生产者 把messageList 发出去
        orderlyProducer.sendOrderlyMessages(messageList, messageQueueNumber);

        return Boolean.TRUE;
    }
}
